<?php

/**
 * LoginForm class.
 * LoginForm is the data structure for keeping
 * user login form data. It is used by the 'login' action of 'SiteController'.
 */
class UUserForm extends CActiveRecord
//class UUserForm extends CFormModel
{
    public $username;
    public $old_password;
    public $password;
    public $password_repeat;
    public $email;


    public function tableName() {
        return UrbacHelper::findModule('urbac')->usersTable;
    }



    /**
     * Declares the validation rules.
     * The rules state that username and password are required,
     * and password needs to be authenticated.
     */
    public function rules() {
        return array(
        // username and password are required
        array('username', 'unique', 'className'=>'Users', 'attributeName'=>'username' ,'message'=>'Nazwa użytkownika jest już zajęta.', 'on'=>'register'),
//        array('email', 'unique', 'className'=>'Users', 'attributeName'=>'username' ,'message'=>'Adres e-mail został juz wykorzystany.', 'on'=>'register'),
        array('username, password, password_repeat, email', 'required', 'on'=>'register'),
        array('old_password, password, password_repeat', 'required', 'on'=>'update'),
        array('password_repeat', 'compare', 'compareAttribute'=>'password', 'message'=>'{attribute} musi być powtórzone dokładnie.' ,'on'=>'register, update'),
        array('email', 'email', 'on'=>'register'),
        array('old_password','oldPasswordCheck', 'on'=>'update'),
        );
    }

    /**
     * Declares attribute labels.
     */
    public function attributeLabels() {
        return array(
        'username'=>'Nazwa użytkownika',
        'old_password'=>'Stare hasło',
        'password'=>'Hasło',
        'password_repeat'=>'Powtórz hasło',
        'email'=>'E-mail',
        );
    }


    public function oldPasswordCheck($attribute,$params)
    {
        if(!$this->hasErrors())  // chcemy uwierzytelniać, tylko wtedy gdy nie ma błędów
        {
            $User = Users::model()->findByPk(Yii::app()->user->id);
            if(UrbacHelper::hashWord($this->old_password) != $User->password)
                $this->addError('old_password','Stare hasło jest niepoprawne.');
        }
    }


}
